<template>
  <div class="content-form-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑内容' : '添加内容' }}</span>
          <el-button @click="$router.go(-1)">返回</el-button>
        </div>
      </template>

      <el-form
        ref="contentFormRef"
        :model="contentForm"
        :rules="contentRules"
        label-width="120px"
        style="width: 100%; max-width: 1200px; margin: 0 auto;"
      >
        <el-form-item label="内容标题" prop="title">
          <el-input
            v-model="contentForm.title"
            placeholder="请输入内容标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="内容类型" prop="type">
          <el-radio-group v-model="contentForm.type">
            <el-radio label="article">文章</el-radio>
            <el-radio label="video">视频</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="内容分类" prop="category">
          <el-select v-model="contentForm.category" placeholder="请选择分类">
            <el-option label="认知提升" value="cognition" />
            <el-option label="健身运动" value="fitness" />
            <el-option label="学习成长" value="learning" />
          </el-select>
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-input v-model="contentForm.author" placeholder="请输入作者姓名" />
        </el-form-item>

        <el-form-item label="封面图片" prop="coverImage">
          <el-upload
            class="cover-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeCoverUpload"
            :http-request="handleCoverUpload"
          >
            <img v-if="contentForm.coverImage" :src="contentForm.coverImage" class="cover-image" />
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：300x200px，支持jpg、png格式</div>
        </el-form-item>

        <el-form-item label="内容摘要" prop="summary">
          <el-input
            v-model="contentForm.summary"
            type="textarea"
            :rows="3"
            placeholder="请输入内容摘要"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="视频链接" prop="videoUrl" v-if="contentForm.type === 'video'">
          <el-input v-model="contentForm.videoUrl" placeholder="请输入视频链接" />
        </el-form-item>

        <el-form-item label="内容正文" prop="content">
          <div class="editor-container">
            <el-input
              v-model="contentForm.content"
              type="textarea"
              :rows="15"
              placeholder="请输入内容正文（支持Markdown格式）"
            />
          </div>
        </el-form-item>

        <el-form-item label="标签">
          <el-tag
            v-for="tag in contentForm.tags"
            :key="tag"
            closable
            @close="handleTagClose(tag)"
            style="margin-right: 10px"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="tagInputVisible"
            ref="tagInputRef"
            v-model="tagInputValue"
            class="tag-input"
            size="small"
            @keyup.enter="handleTagConfirm"
            @blur="handleTagConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showTagInput">
            + 添加标签
          </el-button>
        </el-form-item>

        <el-form-item label="发布状态" prop="status">
          <el-radio-group v-model="contentForm.status">
            <el-radio :label="0">保存为草稿</el-radio>
            <el-radio :label="1">立即发布</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="$router.go(-1)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 响应式数据
const contentFormRef = ref(null)
const tagInputRef = ref(null)
const submitLoading = ref(false)
const tagInputVisible = ref(false)
const tagInputValue = ref('')

// 判断是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 内容表单
const contentForm = reactive({
  id: null,
  title: '',
  type: 'article',
  category: '',
  author: '',
  coverImage: '',
  summary: '',
  videoUrl: '',
  content: '',
  tags: [],
  status: 0
})

// 表单验证规则
const contentRules = {
  title: [
    { required: true, message: '请输入内容标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择内容类型', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择内容分类', trigger: 'change' }
  ],
  author: [
    { required: true, message: '请输入作者姓名', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入内容摘要', trigger: 'blur' },
    { max: 200, message: '摘要长度不能超过 200 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容正文', trigger: 'blur' },
    { min: 50, message: '内容正文至少 50 个字符', trigger: 'blur' }
  ],
  videoUrl: [
    { required: true, message: '请输入视频链接', trigger: 'blur' }
  ]
}

// 生命周期
onMounted(() => {
  if (isEdit.value) {
    fetchContentDetail()
  }
})

// 获取内容详情
const fetchContentDetail = async () => {
  try {
    // 模拟API调用
    setTimeout(() => {
      const mockData = {
        id: route.params.id,
        title: '如何提高认知能力：从思维模式开始',
        type: 'article',
        category: 'cognition',
        author: '张三',
        coverImage: 'https://picsum.photos/300/200?random=1',
        summary: '这是一篇关于认知能力提升的文章，主要介绍了如何通过改变思维模式来提高认知能力。',
        content: '# 如何提高认知能力\n\n认知能力是我们理解和处理信息的能力...',
        tags: ['认知', '思维', '成长'],
        status: 1
      }
      Object.keys(contentForm).forEach(key => {
        if (mockData[key] !== undefined) {
          contentForm[key] = mockData[key]
        }
      })
    }, 500)
  } catch (error) {
    console.error('获取内容详情失败:', error)
    ElMessage.error('获取内容详情失败')
  }
}

// 封面上传前验证
const beforeCoverUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('封面图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('封面图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理封面上传
const handleCoverUpload = (options) => {
  // 模拟上传
  const reader = new FileReader()
  reader.onload = (e) => {
    contentForm.coverImage = e.target.result
    ElMessage.success('封面上传成功')
  }
  reader.readAsDataURL(options.file)
}

// 显示标签输入框
const showTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    tagInputRef.value?.focus()
  })
}

// 确认添加标签
const handleTagConfirm = () => {
  if (tagInputValue.value && !contentForm.tags.includes(tagInputValue.value)) {
    contentForm.tags.push(tagInputValue.value)
  }
  tagInputVisible.value = false
  tagInputValue.value = ''
}

// 删除标签
const handleTagClose = (tag) => {
  const index = contentForm.tags.indexOf(tag)
  if (index > -1) {
    contentForm.tags.splice(index, 1)
  }
}

// 提交表单
const handleSubmit = () => {
  contentFormRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      // 模拟提交操作
      setTimeout(() => {
        ElMessage.success(isEdit.value ? '更新成功' : '保存成功')
        submitLoading.value = false
        router.push('/content/list')
      }, 1000)
    }
  })
}

// 重置表单
const handleReset = () => {
  contentFormRef.value?.resetFields()
  contentForm.tags = []
  contentForm.coverImage = ''
}
</script>

<style scoped>
.content-form-container {
  padding: 20px;
  width: 100%;
  min-width: 900px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.cover-uploader:hover {
  border-color: #409eff;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 118px;
  text-align: center;
  line-height: 118px;
}

.cover-image {
  width: 178px;
  height: 118px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 100%;
}

.editor-container .el-textarea {
  width: 100%;
}

.editor-container .el-textarea__inner {
  width: 100% !important;
  min-width: 600px;
  border: none;
  border-radius: 4px;
}

.tag-input {
  width: 90px;
}

.button-new-tag {
  height: 24px;
  line-height: 22px;
  padding-top: 0;
  padding-bottom: 0;
}
</style>